import { useState } from 'react';
import { Eye, EyeOff, Mail, Lock, Video } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import TitleBar from '@/components/common/TitleBar';
import { clsx } from 'clsx';

interface FormData {
  email: string;
  password: string;
  rememberMe: boolean;
}

const Login: React.FC = () => {
  const { login, isLoading, error } = useAuth();

  const [formData, setFormData] = useState<FormData>({
    email: '',
    password: '',
    rememberMe: false,
  });

  const [showPassword, setShowPassword] = useState(false);
  const [formErrors, setFormErrors] = useState<Partial<FormData>>({});

  const validateForm = (): boolean => {
    const errors: Partial<FormData> = {};

    if (!formData.email) {
      errors.email = '请输入邮箱地址';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      errors.email = '请输入有效的邮箱地址';
    }

    if (!formData.password) {
      errors.password = '请输入密码';
    } else if (formData.password.length < 6) {
      errors.password = '密码至少需要6个字符';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    await login({
      email: formData.email,
      password: formData.password,
      rememberMe: formData.rememberMe,
    });
  };

  const handleInputChange = (field: keyof FormData, value: string | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));

    // Clear field error when user starts typing
    if (formErrors[field]) {
      setFormErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  return (
    <div className='h-screen w-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex flex-col overflow-hidden'>
      {/* Custom Title Bar */}
      <TitleBar title='Movie Tools' />

      <div className='flex-1 flex items-center justify-center px-8'>
        <div className='w-full max-w-md'>
          <div className='bg-white/10 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/20 p-8'>
            <div className='text-center mb-8'>
              <div className='w-16 h-16 bg-gradient-to-br from-purple-500 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-6'>
                <Video className='w-8 h-8 text-white' />
              </div>
              <h1 className='text-3xl font-bold text-white mb-2'>Welcome Back</h1>
              <p className='text-white/70'>Sign in to your account</p>
            </div>

            {error && (
              <div className='p-4 mb-6 bg-red-500/20 backdrop-blur-sm rounded-xl border border-red-500/30'>
                <p className='text-sm text-red-200'>{error}</p>
              </div>
            )}

            <form onSubmit={handleSubmit} className='space-y-6'>
              {/* Email Field */}
              <div>
                <label htmlFor='email' className='block mb-3 text-sm font-medium text-white/90'>
                  Email Address
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <Mail className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='email'
                    name='email'
                    type='email'
                    autoComplete='email'
                    required
                    value={formData.email}
                    onChange={e => handleInputChange('email', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.email && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Enter your email'
                  />
                </div>
                {formErrors.email && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.email}</p>
                )}
              </div>

              {/* Password Field */}
              <div>
                <label htmlFor='password' className='block mb-3 text-sm font-medium text-white/90'>
                  Password
                </label>
                <div className='relative'>
                  <div className='flex absolute inset-y-0 left-0 items-center pl-4 pointer-events-none'>
                    <Lock className='w-5 h-5 text-white/60' />
                  </div>
                  <input
                    id='password'
                    name='password'
                    type={showPassword ? 'text' : 'password'}
                    autoComplete='current-password'
                    required
                    value={formData.password}
                    onChange={e => handleInputChange('password', e.target.value)}
                    className={clsx(
                      'w-full px-4 py-4 pl-12 pr-12 bg-white/10 backdrop-blur-sm border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all duration-300',
                      formErrors.password && 'border-red-400 focus:ring-red-500'
                    )}
                    placeholder='Enter your password'
                  />
                  <button
                    type='button'
                    className='flex absolute inset-y-0 right-0 items-center pr-4 text-white/60 hover:text-white transition-colors'
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className='w-5 h-5' /> : <Eye className='w-5 h-5' />}
                  </button>
                </div>
                {formErrors.password && (
                  <p className='mt-2 text-sm text-red-300'>{formErrors.password}</p>
                )}
              </div>

              {/* Remember Me & Forgot Password */}
              <div className='flex justify-between items-center'>
                <div className='flex items-center'>
                  <input
                    id='rememberMe'
                    name='rememberMe'
                    type='checkbox'
                    checked={formData.rememberMe}
                    onChange={e => handleInputChange('rememberMe', e.target.checked)}
                    className='w-4 h-4 rounded border-white/30 bg-white/10 text-purple-500 focus:ring-purple-500 focus:ring-offset-0'
                  />
                  <label htmlFor='rememberMe' className='block ml-3 text-sm text-white/80'>
                    Remember me
                  </label>
                </div>

                <button
                  type='button'
                  className='text-sm font-medium text-purple-300 hover:text-purple-200 transition-colors'
                >
                  Forgot password?
                </button>
              </div>

              {/* Submit Button */}
              <button
                type='submit'
                disabled={isLoading}
                className='w-full bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold py-4 px-6 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed'
              >
                {isLoading ? (
                  <div className='flex items-center justify-center'>
                    <div className='w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2'></div>
                    Signing in...
                  </div>
                ) : (
                  'Sign In'
                )}
              </button>
            </form>

            {/* Register Link */}
            <div className='mt-8 text-center'>
              <p className='text-sm text-white/70'>
                Don't have an account?{' '}
                <a
                  href='/auth/register'
                  className='text-purple-300 hover:text-purple-200 font-medium transition-colors'
                >
                  Create Account
                </a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
